<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="备件名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入备件名称" />
      </el-form-item>
      <el-form-item label="备件编码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入备件编码" />
      </el-form-item>
      <el-form-item label="备件金额" prop="money">
        <el-input v-model="formData.money" placeholder="请输入备件金额" />
      </el-form-item>
      <el-form-item label="备件状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      
      <el-form-item label="规格型号" prop="model">
        <el-input v-model="formData.model" placeholder="请输入规格型号" />
      </el-form-item>
      <el-form-item label="备件序列" prop="sn">
        <el-input v-model="formData.sn" placeholder="请输入备件序列" />
      </el-form-item>
      <el-form-item label="使用场景" prop="usageRange">
        <el-input v-model="formData.usageRange" placeholder="请输入使用场景" />
      </el-form-item>
      <el-form-item label="存放位置" prop="local">
        <el-input v-model="formData.local" placeholder="请输入存放位置" />
      </el-form-item>
      <el-form-item label="适配信息" prop="adaptingDevice">
        <el-input v-model="formData.adaptingDevice" placeholder="请输入适配信息" />
      </el-form-item>
      <el-form-item label="来源描述" prop="sourceDesc">
        <el-input v-model="formData.sourceDesc" placeholder="请输入来源描述" />
      </el-form-item>
      <el-form-item label="供应厂商" prop="supplier">
        <el-input v-model="formData.supplier" placeholder="请输入供应厂商" />
      </el-form-item>
      <el-form-item label="保管人员" prop="managerUserId">
        <!-- <el-input v-model="formData.name" placeholder="请输入维修工姓名" /> -->
        <el-select filterable v-model="formData.managerUserName" @change="handleChangeUser" class="!w-240px" placeholder="保管人员" clearable>
          <el-option
            v-for="(user, index) in userList"
            :label="user.nickname"
            :value="user"
            :key="index"
            
          />
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="picture">
        <UploadImg v-model="formData.picture"  height="80px" />
      </el-form-item>
      <el-form-item label="数量" prop="spNumber">
        <el-input v-model="formData.spNumber" placeholder="请输入数量" />
      </el-form-item>
      <el-form-item label="入库时间" prop="insertTime">
        <el-date-picker
          v-model="formData.insertTime"
          type="date"
          value-format="x"
          placeholder="选择入库时间"
        />
      </el-form-item>
      <el-form-item label="备注" prop="notes">
        <el-input v-model="formData.notes" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { DeviceSpApi, DeviceSpVO } from '@/api/eam/devicesp'
import * as UserApi from '@/api/system/user'
import {  handleTree } from '@/utils/tree'
import dayjs from 'dayjs'

/** 备件清单 表单 */
defineOptions({ name: 'DeviceSpForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData:any = ref({
  id: undefined,
  code: undefined,
  status: undefined,
  name: undefined,
  model: undefined,
  sn: undefined,
  usageRange: undefined,
  local: undefined,
  adaptingDevice: undefined,
  sourceDesc: undefined,
  supplier: undefined,
  managerUserId: undefined,
  picture: undefined,
  spNumber: undefined,
  insertTime: undefined,
  notes: undefined,
  managerUserName: undefined,
})
const formRules = reactive({
})
const formRef = ref() // 表单 Ref
const userList = ref<UserApi.UserVO[]>([]) // 全量用户清单
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  userList.value = handleTree(await UserApi.getSimpleUserList())
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await DeviceSpApi.getDeviceSp(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as DeviceSpVO
    data.insertTime = data.insertTime ? dayjs(data.insertTime).format('YYYY-MM-DD') : "";
    if (formType.value === 'create') {
      await DeviceSpApi.createDeviceSp(data)
      message.success(t('common.createSuccess'))
    } else {
      await DeviceSpApi.updateDeviceSp(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleChangeUser = (user: UserApi.UserVO) => {
  console.log(user, 'user')
  formData.value.managerUserId = user.id
  formData.value.managerUserName = user.nickname
  
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    status: undefined,
    name: undefined,
    model: undefined,
    sn: undefined,
    usageRange: undefined,
    local: undefined,
    adaptingDevice: undefined,
    sourceDesc: undefined,
    supplier: undefined,
    managerUserId: undefined,
    picture: undefined,
    spNumber: undefined,
    insertTime: undefined,
    notes: undefined,
    managerUserName: undefined,
  }
  formRef.value?.resetFields()
}
</script>